#include "window.h"
#include <cstddef>
#include <iostream>
using namespace std;
/////////////////
//WindowCreator//
/////////////////
Window * WindowCreator::_currentWindow = NULL;
WindowCreator::WindowCreator()
{
}

WindowCreator::~WindowCreator()
{
}

Window* WindowCreator::createWindow(const char *title, int x, int y, int width, int height, int *argc, char **argv)
{
  //initialisation de la glut
  _currentWindow = new Window(x,y,width,height,argc,argv);
  glutCreateWindow(title);
  
  
  glutDisplayFunc(callDisplayFunc);
  glutReshapeFunc(callReshapeFunc);
  glutKeyboardFunc(callKeyboardFunc);
  glutMouseFunc(callMouseFunc);
  glutMotionFunc(callMouseMotionFunc);
  glutPassiveMotionFunc(callMousePassiveMotionFunc);
  glutTimerFunc(40, callTimerFunc, 0);
  return _currentWindow;
}

void WindowCreator::callTimerFunc(int value)
{
  if(_currentWindow && _currentWindow->getScene())
  {
    (_currentWindow->getScene())->_timer(value);
  }
  glutTimerFunc(40, callTimerFunc, 0);
}


void WindowCreator::callDisplayFunc()
{
  if(_currentWindow && _currentWindow->getScene())
  {
    (_currentWindow->getScene())->_display();
  }
}


void WindowCreator::callReshapeFunc(int width, int height)
{
  if(_currentWindow && _currentWindow->getScene())
  {
    (_currentWindow->getScene())->_reshape(width, height);
  }
}

void WindowCreator::callKeyboardFunc(unsigned char key, int x, int y)
{
  if(_currentWindow && _currentWindow->getScene())
  {
    (_currentWindow->getScene())->_keyboard(key, x, y);
  }
}

void WindowCreator::callMouseFunc(int bouton, int etat, int x, int y)
{
  if(_currentWindow && _currentWindow->getScene())
  {
    (_currentWindow->getScene())->_mouse(bouton, etat, x, y);
  }
}

void WindowCreator::callMouseMotionFunc(int x, int y)
{
  if(_currentWindow && _currentWindow->getScene())
  {
    (_currentWindow->getScene())->_mouseMotion(x, y);
  }
}

void WindowCreator::callMousePassiveMotionFunc(int x, int y)
{
  if(_currentWindow && _currentWindow->getScene())
  {
    (_currentWindow->getScene())->_mousePassiveMotion(x, y);
  }
}

void WindowCreator::callMenuCallback(int item)
{
  if(_currentWindow && _currentWindow->getScene())
  {
    (_currentWindow->getScene())->_menuCallback(item);
  }
}

//////////
//Window//
//////////

Window::Window(int x, int y, int width, int height, int *argc, char**argv) : _scene(NULL)
{
  glutInit(argc,argv);
  glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE|GLUT_DEPTH);
  glutInitWindowPosition(x,y);
  glutInitWindowSize(width,height);
}

Window::~Window()
{
}

void Window::mainLoop()
{
  glutMainLoop();
}
void Window::setScene(Scene *s)
{
  _scene = s;
}

Scene* Window::getScene()
{ 
  return _scene;
}

